package com.kfm.am;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBUtils {

    private final String JDBC_URl = "jdbc:mysql://localhost:3306/manager";
    private final String USERNAME = "root";
    private final String PASSWORD = "";

    private Connection connection;
    private PreparedStatement ps;


    // 简化后续的操作 不需要频繁创建连接对象
    public <E> List<E> select(String sql, Handler<E> handler, Object... objects) throws SQLException, ClassNotFoundException {
        // 获取连接
        getConn();
        // 获取执行sql 的对象
        getPreparedStatement(sql);
        // 替换占位符
        setParams(objects);
        // 执行sql
        ResultSet resultSet = ps.executeQuery();
        return handler.handle(resultSet);
    }

    public int update(String sql, Object... objects) throws SQLException, ClassNotFoundException {
        getConn();
        getPreparedStatement(sql);
        setParams(objects);
        return ps.executeUpdate();
    }

    private void setParams(Object... objects) throws SQLException {
        // 替换占位符
        for (int i = 0; i < objects.length; i++) {
            ps.setObject(i + 1, objects[i]);
        }
    }

    private void getConn() throws ClassNotFoundException, SQLException {
        if (connection == null) {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(JDBC_URl, USERNAME, PASSWORD);
        }
    }

    private void getPreparedStatement(String sql) throws SQLException {
        ps = connection.prepareStatement(sql);
    }

    public void close() throws SQLException {
        if (ps != null && !ps.isClosed()) {
            ps.close();
            ps = null;
        }
        if (connection != null && !connection.isClosed()) {
            connection.close();
            connection = null;
        }
    }
}

class Test01 {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        DBUtils dbUtils = new DBUtils();
//        int update = dbUtils.update("insert into books values(4, " +
//                "'三体', '2019-02-03', '刘慈欣', 39.9, 90)");
        List<Book> select = dbUtils.select("select * from books", new Book.BookHandler());
        List<Log> select1 = dbUtils.select("select * from log", new Handler<Log>() {

            @Override
            public List<Log> handle(ResultSet set) throws SQLException {
                List<Log> list = new ArrayList<>();
                while (set.next()) {
                    Log log = new Log();
                    log.setLogId(set.getInt("log_id"));
                    log.setDescription(set.getString("description"));
                    log.setOperationTime(set.getTimestamp("operation_time"));
                    list.add(log);
                }
                return list;
            }
        });
        System.out.println(select1);
//        System.out.println(update > 0 ? "执行成功" : "执行失败");
        dbUtils.close();
    }
}
